package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.AccountRoleEnum;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.OrderInfoEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrderRecordEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrdersEntity;
import com.alinesno.cloud.operation.cmdb.entity.UserEntity;
import com.alinesno.cloud.operation.cmdb.repository.OrderInfoRepository;
import com.alinesno.cloud.operation.cmdb.repository.OrderRecordRepository;
import com.alinesno.cloud.operation.cmdb.repository.OrderRepository;
import com.alinesno.cloud.operation.cmdb.repository.UserRepository;
import com.alinesno.cloud.operation.cmdb.service.OrderService;
import com.alinesno.cloud.operation.cmdb.third.wechat.WechatService;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.OrderRecordEntityExt;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;

/**
 * 后台主面板
 * 
 * @author LuoAnDong
 * @since 2018年8月14日 下午12:58:05
 */
@Controller
@RequestMapping("/manager/")
public class ManagerApplyController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OrderInfoRepository orderInfoRepository; // 订单详情服务

	@Autowired
	private UserRepository userRepository; // 用户服务

	@Autowired
	private OrderRepository orderRepository; // 订单服务
	
	@Autowired
	private OrderService orderService  ;//订单服务 

	@Autowired
	private OrderRecordRepository orderRecordRepository; // 订单记录

	@Autowired
	private WechatService wechatService; // 微信服务

	/**
	 * 订单列表
	 * 
	 * @param model
	 * @param serverId
	 * @return
	 */
	@GetMapping("/order_list")
	public String list(Model model) {
		createMenus(model);
		return WX_MANAGER + "order_list";
	}
	

	/**
	 * 订单列表
	 * 
	 * @param model
	 * @param serverId
	 * @return
	 */
	@GetMapping("/order_add")
	public String apply(Model model) {
		return WX_MANAGER + "order_add";
	}

	@GetMapping("/order_has_pass")
	public String hasPass(Model model) {
		return WX_MANAGER + "order_has_pass";
	}
	
	/**
	 * 订单删除
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@GetMapping("/order_delete")
	public ResponseBean<String> orderDelete(Model model , String orderId) {
		logger.debug("order id = {}" , orderId);
		
		orderInfoRepository.deleteById(orderId);
		
		return ResultGenerator.genFailMessage("删除成功.");
	}

	/**
	 * 订单消息群发
	 * 
	 * @param orderId
	 *            订单id
	 * @return
	 */
	@ResponseBody
	@GetMapping("/order_send_all")
	public ResponseBean<String> sendAll(String orderId, String scope) {

		logger.debug("order send scope = {}", scope);
		Assert.hasLength(scope, "发送范围不能为空.");
		Assert.hasLength(orderId, "订单ID不能为空.");

		if (AccountRoleEnum.ADMIN.getCode().equals(currentManager().getRolePower())) { // 只有超级管理员可以群发
			wechatService.sendTaskMessageToSchoolAllPerson(orderId, scope);
			return ResultGenerator.genSuccessMessage("发送成功.");
		} else {
			return ResultGenerator.genFailMessage("权限不足,请联系超级管理员.");
		}
	}

	/**
	 * 订单详情
	 * 
	 * @param model
	 * @param serverId
	 * @return
	 */
	@GetMapping("/order_detail")
	public String detail(Model model, String orderId) {
		logger.debug("订单号:{}", orderId);
		OrdersEntity order = orderRepository.findByOrderId(orderId) ;  

		List<OrderRecordEntity> recordList = orderRecordRepository.findAllByOrderId(orderId,Sort.by(Direction.ASC, "addTime"));
		List<OrderRecordEntityExt> recordExtList = new ArrayList<OrderRecordEntityExt>();

		for (OrderRecordEntity e : recordList) {
			OrderRecordEntityExt ee = new OrderRecordEntityExt();
			BeanUtils.copyProperties(e, ee);

			if (StringUtils.isNoneBlank(e.getActionMan())) {
				Optional<UserEntity> userOpt = userRepository.findById(e.getActionMan());
				if (userOpt.isPresent()) {
					UserEntity u = userOpt.get();
					ee.setUserName(StringUtils.isBlank(u.getRealName()) ? u.getNickname() : u.getRealName());
					ee.setPhone(u.getPhone());
				}
			}

			recordExtList.add(ee);
		}

		model.addAttribute("order", order);
		model.addAttribute("list", recordExtList);
		return WX_MANAGER + "order_detail";
	}

	/**
	 * 数据列表
	 * 
	 * @return
	 */
	@ConvertCode
	@SuppressWarnings("unchecked")
	@ResponseBody
	@GetMapping("/order_list_data")
	public Object orderListData(Model model, JqDatatablesPageBean page) {

		JqDatatablesPageBean listPage = this.toPage(model, page.buildFilter(OrderInfoEntity.class, request) , orderInfoRepository, page);
		
//		List<OrderInfoBean> orderList = new ArrayList<OrderInfoBean>();
//
//		for (OrdersEntity o : (List<OrdersEntity>) listPage.getData()) {
//			OrderInfoEntity orderInfo = orderInfoRepository.findById(o.getInfoId()).get();
//			OrderInfoBean bean = new OrderInfoBean();
//			BeanUtils.copyProperties(o, bean);
//			BeanUtils.copyProperties(orderInfo, bean);
//			bean.setGoodsName(bean.getGoodsName().replace("#", "<br/>"));
//			setSendStatus(bean);
//			orderList.add(bean);
//		}
//
//		listPage.setData(orderList);
		
		return listPage;
	}
	
	/**
	 * 主机申请保存 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/order_apply_save" , method = RequestMethod.POST)
	public ResponseBean<String> saveAdd(Model model , OrderInfoEntity bean , String resources , HttpServletRequest request) {
		
		// 查看是否已经存在登陆名
		bean.setMasterCode(currentManager().getMasterCode());
		boolean b = orderInfoRepository.save(bean) != null ; //save(bean , resources , request.getRemoteHost()) ; 
		
		return b?ResultGenerator.genSuccessMessage("保存成功."):ResultGenerator.genFailMessage("保存失败.") ; 
	}

	/**
	 * 主机申请通过
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/order_apply_pass" , method = RequestMethod.POST)
	public ResponseBean<String> savePass(Model model , String orderInfoId , HttpServletRequest request , String machineIds) {
		
		if(StringUtils.isBlank(orderInfoId) || StringUtils.isBlank(machineIds)) {
			return ResultGenerator.genFailMessage("保存失败.") ;
		}
	
		boolean b = orderService.applyPass(orderInfoId , machineIds) ; 
		
		return b?ResultGenerator.genSuccessMessage("保存成功."):ResultGenerator.genFailMessage("保存失败.") ; 
	}

}
